package com.guli.seckill.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberRespVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean isMatch = antPathMatcher.match("/kill", request.getRequestURI());

        if (isMatch) {
            Object obj = request.getSession().getAttribute("loginUser");
            MemberRespVo loginUser = JSON.parseObject(JSON.toJSONString(obj), new TypeReference<MemberRespVo>() {
            });
            if (loginUser != null) {
                //已登录
                threadLocal.set(loginUser);
                return true;
            } else {
                //没登录就去登录
                request.getSession().setAttribute("msg", "请先进行登录");
                response.sendRedirect("http://auth.gulimall.com/login");
                return false;
            }
        }
        return true;
    }
}
